Medium
Given an asynchronous function fn
and a time t
in milliseconds, return a new time limited version of the input function.fn
takes arguments provided to the time limited function.
The time limited function should follow these rules:
If the fn
completes within the time limit of t
milliseconds, the time limited function should resolve with the result.
If the execution of the fn
exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded"
.
給定非同步函數fn
和以毫秒為單位的時間t
作為參數,返回一個對輸入函數fn
添加時間限制版本的新函數。
原始函數fn
會使用限時函數(time limited function)所傳遞的參數進行調用。
限時函數應遵循以下規則:
如果 fn
在 t
毫秒的時間限制內完成,則限時函數應解析結果。
如果 fn
的執行時間超過t毫秒的限時,則時間限制函數應拒絕並顯示字串"Time Limit Exceeded"
。
function timeLimit(fn, t) {
return (...args) => {
const originalPromise = fn(...args);
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject("Time Limit Exceeded");
}, t);
});
return Promise.race([originalPromise, timeoutPromise]);
};
}
const fn1 = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
const inputs1 = [5];
const t1 = 50;
const test1 = timeLimit(fn1, t1);
test1(...inputs1)
.then(result => { console.log(result); })
.catch(error => { console.error(error); });
//輸出:Time Limit Exceeded
const fn2 = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
const inputs2 = [5];
const t2 = 150;
const test2 = timeLimit(fn2, t2);
test2(...inputs2)
.then(result => { console.log(result); })
.catch(error => { console.error(error); });
//輸出:25
const fn3 = async (a, b) => {
await new Promise(res => setTimeout(res, 120));
return a + b;
}
const inputs3 = [5, 10];
const t3 = 150;
const test3 = timeLimit(fn3, t3);
test3(...inputs3)
.then(result => { console.log(result); })
.catch(error => { console.error(error); });
//輸出:15
const fn4 = async () => {
throw "Error";
}
const inputs4 = [];
const t4 = 1000;
const test4 = timeLimit(fn4, t4);
test4(...inputs4)
.then(result => { console.log(result); })
.catch(error => { console.error(error); });
//輸出:Error